package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")//别忘了这个最重要的标记
public class BlogServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();//转成json格式用的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //目的是为了获取博客列表和博客详情页
        //如果请求里有bolgId就返回详情页，没有就返回列表
        BlogDao blogDao = new BlogDao();
        resp.setContentType("application/json; charset=utf8");//这个主要是针对返回的内容设置格式和编码
        String param = req.getParameter("blogId");

        if (param == null){
            //没有blogId，返回列表页
            List<Blog> blogs = blogDao.selectAll();
            String blogsJson = objectMapper.writeValueAsString(blogs);//JSON格式
            resp.getWriter().write(blogsJson);
        }else {
            int blogId = Integer.parseInt(param);//先获取blogId
            Blog blog = blogDao.selectOne(blogId);//根据这个id获取博客
            String blogJson = objectMapper.writeValueAsString(blog);//再把这个博客转成JSON就行
            resp.getWriter().write(blogJson);
        }
    }

    //提交博客
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //基本上用到post就要设置请求报文的格式
        req.setCharacterEncoding("utf8");

        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if (title == null || "".equals(title) || content == null || "".equals(content)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("提交博客失败，缺少参数");
            return;
        }

        //构造一个Blog对象
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);

        //获取UserId还要先获取会话
        HttpSession session = req.getSession(false);
        if (session == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }
        User user = (User) session.getAttribute("user");
        blog.setUserId(user.getUserId());

        //最后插入到数据库中
        BlogDao blogDao = new BlogDao();
        UserDao userDao = new UserDao();
        userDao.updatePlus(user.getUserId());
        blogDao.insert(blog);
        resp.sendRedirect("blog_list.html");
    }
}
